package com.coocaa.launcher.statusplugins.bluetooth;

import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import com.coocaa.launcher.framework.launcherhost.statusbar.StatusBarPlugin;
import com.coocaa.launcher.framework.launcherhost.statusbar.StatusBarPluginView;
import com.coocaa.x.framework.utils.LogUtils;

/**
 * Created by lu on 15-6-15.
 */
public class StatusPluginBluetooth extends StatusBarPlugin {
    public static interface IStatusPluginBluetooth {
        void onBind(boolean value);
    }

    public static StatusPluginBluetooth instance = new StatusPluginBluetooth();
    private StatusPluginBluetoothView view = null;
    BluetoothAdapter adapter;

    public StatusPluginBluetooth() {
        super("statusplugin.bluetooth");
    }


    @Override
    protected void onCreate() {
        super.onCreate();
        LogUtils.d("statusplugin", "sunny Bluetooth boot onCreate");
        try {
            IntentFilter filter = new IntentFilter();
            filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
            mContext.registerReceiver(receiver, filter);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        LogUtils.d("statusplugin", "sunny Bluetooth boot onDestroy");
        try{
            mContext.unregisterReceiver(receiver);
        }catch (Exception e){
            e.printStackTrace();
        }
        super.onDestroy();
    }

    @Override
    public synchronized StatusBarPluginView inflate(String pattern) {
        if (view == null)
            view = new StatusPluginBluetoothView(mContext, getName());
        postAction(runnable, 1000);
        return view;
    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            if(adapter == null)
                adapter = BluetoothAdapter.getDefaultAdapter();
            if (adapter != null && adapter.isEnabled() && view!= null) {
                view.onBind(true);
            } else if(view != null){
                view.onBind(false);
            }
        }
    };

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            LogUtils.d("statusplugin", "sunny Bluetooth action :" + action);
            postAction(runnable, 1000);
        }
    };
}
